<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use DB;
use App\Http\Requests\NoticeRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class NoticeController extends Controller
{

	//用户添加da
    public function getAdd()
    {
    	//解析模板
    	return view('Admin.notice.add');
    }

    //执行用户添加
    public function postInsert(NoticeRequest $request)
    {

        //接收数据
        $data = $request->only(['title','content','author']);
        $data['time'] = date('Y-m-d H:i:s',time());
        $data['status'] = 1;//未使用
        //插入数据库
        $res = DB::table('notice')->insert($data);
        //判断
        if($res){
            return redirect('/admin/notice/index')->with('success','添加成功');
        }else{
            return back()->with('error','添加失败');
        }
    }

    //公告列表
    public function getIndex(Request $request)
    {
        //条件查询数据
        $num = $request->input('num',10);
        if($request->input('author')){
            $data = DB::table('notice')->where('author','like','%'.$request->input('author').'%')->paginate($num);
        }else{
            //查询所有数据  分页
            $data = DB::table('notice')->paginate($num);
        }
        //限制分页
        $all = $request->all();
        //解析模板
        return view('admin.notice.index',['notice'=>$data,'request'=>$all]);
    }

    //ajax 删除
    public function postDelete(Request $request)
    {
        $id = $request->input('id');
        //删除
        $res = DB::table('notice')->where('id',$id)->delete();
        //判断
        if($res){
            echo 1;
        }else{
            echo 0;
        }
    }

    //修改
    public function getEdit($id)
    {
        //查询数据
        $res = DB::table('notice')->where('id',$id)->first();

        return view('admin.notice.edit',['notice'=>$res]);
    }

    //执行修改
    public function postUpdate(Request $request)
    {

        //接收数据
        $data = $request->only(['title','content','author','status']);
        //隐藏域的
        $data1 = $request->only(['title1','content1','author1','status1']);

        //不修改的时候 也成功
        if(array_values($data) == array_values($data1)){
            return redirect('/admin/notice/index')->with('success','修改成功');
        }else{
           //修改
            $res = DB::table('notice')->where('id',$request->input('id'))->update($data);
            //判断
            if($res){
                return redirect('/admin/notice/index')->with('success','修改成功');
            }else{
                return back()->with('error','修改失败');
            }
        }
 
    }
    
}
